<template>
  <view class="login-container">
    <view class="login-header">
      <view class="login-logo">
        <image src="/static/logo.png" mode="aspectFit"></image>
        <text class="logo-text">MoeConnect</text>
      </view>
      <text class="login-title">欢迎回来</text>
      <text class="login-subtitle">请登录您的账户</text>
      
      <!-- 美化的服务器状态显示 -->
      <view class="connection-status-enhanced">
        <view class="status-content">
          <view :class="['status-indicator', serverStatus]">
            <view class="status-pulse"></view>
          </view>
          <text class="status-text">{{ statusText }}</text>
        </view>
        <button class="refresh-btn-enhanced" @click="refreshServerStatus" :disabled="isRefreshing">
          <text>{{ isRefreshing ? '检查中...' : '刷新' }}</text>
        </button>
      </view>
    </view>
    
    <view class="form-content">
      <view class="form-group">
        <text class="form-label">邮箱</text>
        <view class="input-wrapper">
          <text class="input-icon">✉️</text>
          <input 
            id="login-email" 
            v-model="formData.email" 
            type="text" 
            class="form-input" 
            placeholder="请输入邮箱"
            :autocomplete="'email'"
            :auto-focus="false"
            @input="onEmailInput"
            @blur="onEmailBlur"
          />
          <!-- APP端自动填充按钮 -->
          <!-- #ifdef APP-PLUS -->
          <text class="auto-fill-btn" @click="autoFillEmail" v-if="availableEmails.length > 0">
            📋
          </text>
          <!-- #endif -->
        </view>
      </view>

      <view class="form-group">
        <text class="form-label">密码</text>
        <view class="input-wrapper">
          <text class="input-icon">🔒</text>
          <input 
            id="login-password"
            v-model="formData.password" 
            :type="showPassword ? 'text' : 'password'" 
            class="form-input" 
            placeholder="请输入密码"
            :autocomplete="'current-password'"
            @input="onPasswordInput"
            @blur="onPasswordBlur"
          />
          <text
            class="toggle-password"
            @click="showPassword = !showPassword"
          >{{ showPassword ? '👁️' : '🙈' }}</text>
          <!-- APP端自动填充按钮 -->
          <!-- #ifdef APP-PLUS -->
          <text class="auto-fill-btn" @click="autoFillPassword" v-if="formData.email && !formData.password">
            🔑
          </text>
          <!-- #endif -->
        </view>
        <!-- 邮箱自动填充建议列表 -->
        <view v-if="showAutoFillMenu && autoFillSuggestions.length > 0" class="auto-fill-suggestions">
          <view 
            v-for="(suggestion, index) in autoFillSuggestions" 
            :key="index"
            class="suggestion-item"
            @click="selectEmailSuggestion(suggestion)"
          >
            <text class="suggestion-text">{{ suggestion }}</text>
          </view>
        </view>
      </view>

      <button type="button" class="btn-primary auth-btn" :disabled="isLoading" @click="handleLogin">
        <template v-if="isLoading">
          <text class="loading-icon">⏳</text>
          <text>登录中...</text>
        </template>
        <template v-else>登录</template>
      </button>
      
      <view v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </view>
      
      <view v-if="successMessage" class="success-message">
        {{ successMessage }}
      </view>
      
      <!-- 微信登录按钮 -->
      <view class="wechat-login-section">
        <view class="divider">
          <view class="divider-line"></view>
          <text class="divider-text">或</text>
          <view class="divider-line"></view>
        </view>
        <button 
          type="button" 
          class="btn-wechat" 
          :disabled="isWechatLoading" 
          @click="handleWechatLogin"
        >
          <template v-if="isWechatLoading">
            <text class="loading-icon">⏳</text>
            <text>微信登录中...</text>
          </template>
          <template v-else>
            <text class="wechat-icon">💬</text>
            <text>微信登录</text>
          </template>
        </button>
      </view>
      
      <!-- 找回密码和注册链接 -->
      <view class="auth-links">
        <text class="forgot-password-btn" @click="showForgotPasswordModal">忘记密码？</text>
        <view class="register-link">
          <text class="register-text">还没有账号？</text>
          <text class="register-btn" @click="navigateToRegister">立即注册</text>
        </view>
      </view>
    </view>

    <!-- 找回密码弹窗 -->
    <view v-if="showForgotPassword" class="modal-overlay" @click="closeForgotPasswordModal">
      <view class="modal-content forgot-password-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">找回密码</text>
          <text class="modal-close" @click="closeForgotPasswordModal">✕</text>
        </view>
        <view class="modal-body">
          <view class="forgot-password-info">
            <text class="info-text">请输入您的邮箱地址，我们将显示本地存储的密码（仅限本地模式）</text>
          </view>
          
          <view class="form-group">
            <text class="form-label">邮箱地址</text>
            <view class="input-wrapper">
              <text class="input-icon">✉️</text>
              <input 
                v-model="forgotPasswordEmail" 
                type="email" 
                class="form-input" 
                placeholder="请输入注册时的邮箱" 
              />
            </view>
          </view>
          
          <view v-if="foundPassword" class="password-result">
            <text class="result-label">找到的密码：</text>
            <view class="password-display">
              <text class="password-text">{{ foundPassword }}</text>
              <text class="copy-btn" @click="copyPassword">复制</text>
            </view>
          </view>
          
          <view v-if="passwordNotFound" class="no-password-result">
            <text class="no-password-text">未找到该邮箱的本地密码记录</text>
            <view v-if="availableEmails.length > 0" class="available-emails">
              <text class="available-emails-title">本地已注册的邮箱：</text>
              <view v-for="email in availableEmails" :key="email" class="email-item">
                <text class="email-text" @click="selectEmail(email)">{{ email }}</text>
              </view>
            </view>
            <view class="manual-password-section">
              <text class="manual-password-title">如果这是您的账户，可以手动设置密码：</text>
              <view class="manual-password-input">
                <input 
                  v-model="manualPassword" 
                  type="password" 
                  class="form-input" 
                  placeholder="请输入密码" 
                />
                <button class="set-password-btn" @click="setManualPassword">设置密码</button>
              </view>
            </view>
          </view>
          
          <view class="modal-actions">
            <button class="modal-btn secondary" @click="closeForgotPasswordModal">
              取消
            </button>
            <button class="modal-btn primary" @click="searchPassword" :disabled="!forgotPasswordEmail.trim()">
              查找密码
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import apiService from '../../../utils/api-service.js'
import appStateManager from '../../../utils/app-state-manager.js'
import config from '../../../utils/config.js'

export default {
  data() {
    return {
      formData: {
        email: '',
        password: ''
      },
      isLoading: false,
      errorMessage: '',
      successMessage: '',
      serverStatus: 'offline',
      statusText: '正在检查服务器状态...',
      isRefreshing: false,
      showPassword: false,
      // 微信登录相关
      isWechatLoading: false,
      // 找回密码相关
      showForgotPassword: false,
      forgotPasswordEmail: '',
      foundPassword: '',
      passwordNotFound: false,
      availableEmails: [],
      manualPassword: '',
      // 自动填充相关
      autoFillSuggestions: [],
      showAutoFillMenu: false
    }
  },
  
  onLoad(options) {
    appStateManager.subscribe('server', (serverState) => {
      this.isServerOnline = serverState.isOnline
      this.updateServerStatusDisplay() // 状态变化时更新显示
    })
    
    // 处理微信登录回调
    this.handleWechatCallback(options)
    
    // 如果从注册页面跳转过来，自动填充邮箱
    if (options && options.email && !options.success) {
      this.formData.email = options.email
    }
    
    // 加载可用的邮箱列表用于自动填充
    this.loadAvailableEmails()
    
    // 自动检查服务器状态
    this.refreshServerStatus()
  },
  
  // 页面显示时自动检查服务器状态
  onShow() {
    // 页面切换到登录页时自动检查服务器状态
    this.refreshServerStatus()
  },
  
  methods: {
    async handleLogin() {
      // 验证表单
      if (!this.formData.email) {
        uni.showToast({
          title: '请输入邮箱地址',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }
      
      this.isLoading = true
      this.errorMessage = ''
      this.successMessage = ''
      
      try {
        // 如果服务器在线，优先尝试服务器登录
        const serverStatus = appStateManager.getState("server")
        if (serverStatus.isOnline) {
          try {
            const response = await apiService.login({
              email: this.formData.email,
              password: this.formData.password
            })
            
            if (response.data) {
              // 服务器登录成功
              const userData = {
                id: response.data.user.id,
                name: response.data.user.name,
                email: response.data.user.email,
                role: response.data.user.role || 'user',
                created_at: response.data.user.created_at,
                avatar: response.data.user.avatar || ''
              }
              
              // 清除其他用户的本地数据，确保数据隔离
              this.clearOtherUserData(userData.id)
              
              // 保存用户信息到本地存储
              uni.setStorageSync('user_token', response.data.token || `token_${userData.id}_${Math.floor(Date.now() / 3600000)}`)
              uni.setStorageSync('currentUser', JSON.stringify(userData))
              uni.setStorageSync('currentToken', JSON.stringify(response.data.token))
              uni.setStorageSync('isServerLogin', JSON.stringify(true))
              
              // 同步到本地用户列表
              this.syncUserToLocal(userData)
              
              this.successMessage = '登录成功！（服务器数据）'
              
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              })
              
              // 延迟跳转到首页
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/index/index'
                })
              }, 1500)
              return
            }
          } catch (serverError) {
            console.log('服务器登录失败，尝试本地登录:', serverError.message)
            
            // 解析服务器错误信息，如果是特定错误（如账户被封禁），直接显示错误，不尝试本地登录
            if (serverError.message) {
              try {
                const errorData = JSON.parse(serverError.message)
                if (errorData.code && errorData.message) {
                  // 如果是账户被封禁等特定错误，直接显示服务器错误信息
                  if (errorData.code === 'ACCOUNT_BANNED' || errorData.code === 'INVALID_CREDENTIALS') {
                    this.errorMessage = errorData.data?.details || errorData.message
                    uni.showModal({
                      title: errorData.message,
                      content: errorData.data?.details || errorData.message + (errorData.data?.suggestion ? '\n\n建议：' + errorData.data.suggestion : ''),
                      showCancel: false,
                      confirmText: '知道了'
                    })
                    return
                  }
                }
              } catch (parseError) {
                // 如果不是JSON格式，继续尝试本地登录
                console.log('解析服务器错误信息失败:', parseError)
              }
            }
          }
        }
        
        // 尝试本地登录
        const localResult = await this.tryLocalLogin(this.formData.email, this.formData.password)
        if (localResult) {
          const serverStatus = appStateManager.getState("server")
          const statusText = serverStatus.isOnline ? 
            '（本地数据，建议同步到服务器）' : 
            '（本地模式）'
          
          this.successMessage = `登录成功！${statusText}`
          
          // 清除其他用户的本地数据，确保数据隔离
          this.clearOtherUserData(localResult.user.id)
          
          // 保存用户信息到本地存储
          uni.setStorageSync('user_token', localResult.token)
          uni.setStorageSync('currentUser', JSON.stringify(localResult.user))
          uni.setStorageSync('currentToken', JSON.stringify(localResult.token))
          uni.setStorageSync('isServerLogin', JSON.stringify(false))
          
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          
          // 如果服务器在线但使用本地数据，显示同步提示
          if (serverStatus.isOnline) {
            setTimeout(() => {
              uni.showModal({
                title: '数据同步',
                content: '检测到您使用的是本地数据，但服务器在线。是否要同步数据到服务器？',
                success: (res) => {
                  if (res.confirm) {
                    this.syncToServer(localResult.user)
                  }
                }
              })
            }, 1000)
          }
          
          // 延迟跳转到首页
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/index/index'
            })
          }, 1500)
          return
        }
        
        // 如果都失败了
        this.errorMessage = '邮箱或密码错误'
        uni.showModal({
          title: '登录失败',
          content: '邮箱或密码错误，请检查输入信息是否正确',
          showCancel: false,
          confirmText: '知道了'
        })
        
      } catch (error) {
        console.error('登录失败:', error)
        
        // 解析服务器返回的详细错误信息
        let errorTitle = '登录失败'
        let errorMessage = '请重试'
        
        if (error.message) {
          // 如果是服务器返回的结构化错误信息
          try {
            const errorData = JSON.parse(error.message)
            if (errorData.code && errorData.message) {
              errorTitle = errorData.message
              errorMessage = errorData.data?.details || errorData.message
              
              // 如果有建议信息，也显示出来
              if (errorData.data?.suggestion) {
                errorMessage += '\n\n建议：' + errorData.data.suggestion
              }
            }
          } catch (parseError) {
            // 如果不是JSON格式，直接使用错误信息
            errorTitle = '登录失败'
            errorMessage = error.message
          }
        }
        
        this.errorMessage = errorMessage
        uni.showModal({
          title: errorTitle,
          content: errorMessage,
          showCancel: false,
          confirmText: '知道了'
        })
      } finally {
        this.isLoading = false
      }
    },
    
    // 尝试本地登录
    async tryLocalLogin(email, password) {
      const users = uni.getStorageSync('users')
      if (!users) {
        return null
      }
      
      const userList = JSON.parse(users)
      const user = userList.find(u => u.email === email && u.password === password)
      
      if (user) {
        const token = `token_${user.id}_${Math.floor(Date.now() / 3600000)}`
        return {
          user: {
            id: user.id,
            name: user.name,
            email: user.email,
            role: user.role || 'user',
            created_at: user.created_at || user.createdAt,
            avatar: user.avatar || ''
          },
          token: token
        }
      }
      return null
    },
    
    // 同步用户数据到本地存储
    syncUserToLocal(user) {
      console.log('登录页面同步用户数据到本地:', user)
      
      const users = uni.getStorageSync('users')
      let userList = []
      
      if (users) {
        userList = JSON.parse(users)
      }
      
      const existingIndex = userList.findIndex(u => u.id === user.id || u.email === user.email)
      
      if (existingIndex !== -1) {
        // 保留现有用户的密码（如果新用户数据没有密码字段）
        const existingPassword = userList[existingIndex].password
        userList[existingIndex] = { ...userList[existingIndex], ...user }
        // 如果新用户数据没有密码，保留原有的密码
        if (!user.password && existingPassword) {
          userList[existingIndex].password = existingPassword
        }
      } else {
        userList.push(user)
      }
      
      console.log('登录页面保存到本地的用户列表:', userList)
      uni.setStorageSync('users', JSON.stringify(userList))
    },
    
    // 同步数据到服务器
    async syncToServer(user) {
      try {
        const response = await apiService.register({
          name: user.name,
          email: user.email,
          password: '123456' // 这里应该使用原始密码，但为了安全，使用默认密码
        })
        
        if (response.data) {
          uni.showToast({
            title: '数据已同步到服务器！',
            icon: 'success'
          })
          // 更新用户信息，标记为服务器登录
          uni.setStorageSync('currentUser', JSON.stringify(response.data.user))
          uni.setStorageSync('isServerLogin', JSON.stringify(true))
        }
      } catch (error) {
        console.error('同步到服务器失败:', error)
        uni.showToast({
          title: '同步到服务器失败，请稍后重试',
          icon: 'error'
        })
      }
    },
    
    
    updateServerStatusDisplay() {
      const status = appStateManager.getState("server")
      this.serverStatus = status.isOnline ? 'online' : 'offline'
      this.statusText = status.isOnline ? '服务器连接正常' : '服务器连接异常'
    },
    
    async refreshServerStatus() {
      if (this.isRefreshing) return
      
      this.isRefreshing = true
      try {
        await apiService.refreshServerStatus()
        this.updateServerStatusDisplay()
        
        uni.showToast({
          title: this.serverStatus === 'online' ? '服务器连接正常' : '服务器连接异常',
          icon: this.serverStatus === 'online' ? 'success' : 'none'
        })
      } catch (error) {
        console.error('刷新服务器状态失败:', error)
        uni.showToast({
          title: '刷新失败',
          icon: 'error'
        })
      } finally {
        this.isRefreshing = false
      }
    },
    
    navigateToRegister() {
      uni.navigateTo({
        url: '/pages/auth/register/register'
      })
    },
    
    // ========== 微信登录相关方法 ==========
    /**
     * 处理微信登录回调
     */
    handleWechatCallback(options) {
      if (!options) {
        // 尝试从URL参数中获取（H5平台）
        // #ifdef H5
        if (typeof window !== 'undefined' && window.location) {
          // 手动解析URL参数（兼容uni-app环境）
          const search = window.location.search.substring(1)
          if (search) {
            const params = {}
            search.split('&').forEach(param => {
              const [key, value] = param.split('=')
              if (key) {
                params[decodeURIComponent(key)] = value ? decodeURIComponent(value) : ''
              }
            })
            const success = params.success
            const user = params.user
            const message = params.message
            
            if (success || user || message) {
              options = { success, user, message }
            }
          }
        }
        // #endif
        
        if (!options) return
      }
      
      const success = options.success
      const user = options.user
      const message = options.message
      
      if (success === 'true' && user) {
        // 微信登录成功
        try {
          // 处理URL编码的用户信息
          let userInfoStr = user
          if (typeof decodeURIComponent === 'function') {
            try {
              userInfoStr = decodeURIComponent(user)
            } catch (e) {
              console.log('URL解码失败，尝试直接解析:', e)
            }
          }
          
          const userInfo = JSON.parse(userInfoStr)
          console.log('微信登录成功，用户信息:', userInfo)
          
          // 处理微信用户信息并登录
          this.processWechatLogin(userInfo)
          
          // 清除URL参数
          // #ifdef H5
          if (typeof window !== 'undefined' && window.history) {
            window.history.replaceState({}, document.title, window.location.pathname)
          }
          // #endif
        } catch (e) {
          console.error('解析微信用户信息失败:', e)
          console.error('原始用户信息:', user)
          uni.showModal({
            title: '登录失败',
            content: '解析用户信息失败，请重试',
            showCancel: false
          })
        }
      } else if (success === 'false') {
        // 微信登录失败
        let errorMsg = message || '登录失败'
        if (typeof decodeURIComponent === 'function') {
          try {
            errorMsg = decodeURIComponent(errorMsg)
          } catch (e) {
            console.log('URL解码失败:', e)
          }
        }
        
        console.error('微信登录失败:', errorMsg)
        uni.showModal({
          title: '微信登录失败',
          content: errorMsg,
          showCancel: false,
          confirmText: '知道了'
        })
        
        // 清除URL参数
        // #ifdef H5
        if (typeof window !== 'undefined' && window.history) {
          window.history.replaceState({}, document.title, window.location.pathname)
        }
        // #endif
      }
    },
    
    /**
     * 处理微信登录
     */
    async handleWechatLogin() {
      if (this.isWechatLoading) return
      
      this.isWechatLoading = true
      this.errorMessage = ''
      this.successMessage = ''
      
      try {
        // 微信登录必须使用生产服务器地址（确保回调域名正确）
        const backendURL = config.getProductionServerURL()
        const authUrlEndpoint = `${backendURL}/wechat/auth-url`
        
        console.log('获取微信授权链接:', authUrlEndpoint)
        
        // 调用后端接口获取微信授权链接
        const response = await uni.request({
          url: authUrlEndpoint,
          method: 'GET',
          timeout: 10000
        })
        
        if (response.statusCode === 200 && response.data && response.data.success) {
          const authURL = response.data.data.url
          console.log('微信授权链接:', authURL)
          
          // 跳转到微信授权页面
          // #ifdef H5
          if (typeof window !== 'undefined') {
            window.location.href = authURL
          }
          // #endif
          
          // #ifdef APP-PLUS
          if (typeof plus !== 'undefined' && plus.runtime) {
            plus.runtime.openURL(authURL)
          } else {
            uni.showModal({
              title: '提示',
              content: '请在浏览器中打开此链接进行微信登录',
              showCancel: false
            })
          }
          // #endif
        } else {
          throw new Error(response.data?.message || '获取授权链接失败')
        }
      } catch (error) {
        console.error('微信登录失败:', error)
        this.isWechatLoading = false
        
        let errorMessage = '获取微信授权链接失败，请重试'
        if (error.message) {
          errorMessage = error.message
        } else if (error.errMsg) {
          if (error.errMsg.includes('timeout')) {
            errorMessage = '请求超时，请检查网络连接'
          } else if (error.errMsg.includes('fail')) {
            errorMessage = '网络请求失败，请检查服务器连接'
          }
        }
        
        uni.showModal({
          title: '微信登录失败',
          content: errorMessage,
          showCancel: false,
          confirmText: '知道了'
        })
      }
    },
    
    /**
     * 处理微信登录成功后的用户信息
     */
    async processWechatLogin(wechatUserInfo) {
      try {
        uni.showLoading({
          title: '正在登录...',
          mask: true
        })
        
        // 构建用户数据
        const userData = {
          id: wechatUserInfo.openid || `wechat_${Date.now()}`,
          name: wechatUserInfo.nickname || '微信用户',
          email: wechatUserInfo.openid ? `${wechatUserInfo.openid}@wechat.local` : `wechat_${Date.now()}@wechat.local`,
          role: 'user',
          avatar: wechatUserInfo.headimgurl || '',
          openid: wechatUserInfo.openid,
          province: wechatUserInfo.province || '',
          city: wechatUserInfo.city || '',
          loginType: 'wechat',
          created_at: new Date().toISOString()
        }
        
        // 检查服务器是否在线，尝试同步到服务器
        const serverStatus = appStateManager.getState("server")
        if (serverStatus.isOnline) {
          try {
            // 尝试通过微信信息注册或登录到服务器
            // 这里可以根据实际后端API调整
            const response = await apiService.register({
              name: userData.name,
              email: userData.email,
              password: `wechat_${wechatUserInfo.openid}_${Date.now()}` // 生成一个随机密码
            })
            
            if (response.data && response.data.user) {
              // 服务器注册成功，使用服务器返回的用户信息
              userData.id = response.data.user.id
              userData.email = response.data.user.email
              userData.name = response.data.user.name
              
              // 保存token
              uni.setStorageSync('user_token', response.data.token || `token_${userData.id}_${Math.floor(Date.now() / 3600000)}`)
              uni.setStorageSync('isServerLogin', JSON.stringify(true))
            }
          } catch (serverError) {
            console.log('服务器注册失败，使用本地登录:', serverError.message)
            // 服务器注册失败，使用本地登录
            uni.setStorageSync('isServerLogin', JSON.stringify(false))
          }
        } else {
          uni.setStorageSync('isServerLogin', JSON.stringify(false))
        }
        
        // 清除其他用户的本地数据，确保数据隔离
        this.clearOtherUserData(userData.id)
        
        // 保存用户信息到本地存储
        const token = uni.getStorageSync('user_token') || `token_${userData.id}_${Math.floor(Date.now() / 3600000)}`
        uni.setStorageSync('user_token', token)
        uni.setStorageSync('currentUser', JSON.stringify(userData))
        uni.setStorageSync('currentToken', JSON.stringify(token))
        
        // 同步到本地用户列表
        this.syncUserToLocal(userData)
        
        uni.hideLoading()
        
        this.successMessage = '微信登录成功！'
        uni.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 2000
        })
        
        // 延迟跳转到首页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index/index'
          })
        }, 1500)
        
      } catch (error) {
        uni.hideLoading()
        console.error('处理微信登录失败:', error)
        uni.showModal({
          title: '登录失败',
          content: error.message || '处理用户信息失败，请重试',
          showCancel: false,
          confirmText: '知道了'
        })
      }
    },
    
    // 找回密码相关方法
    showForgotPasswordModal() {
      this.showForgotPassword = true
      this.forgotPasswordEmail = this.formData.email // 预填充当前输入的邮箱
      this.foundPassword = ''
      this.passwordNotFound = false
    },
    
    closeForgotPasswordModal() {
      this.showForgotPassword = false
      this.forgotPasswordEmail = ''
      this.foundPassword = ''
      this.passwordNotFound = false
      this.availableEmails = []
      this.manualPassword = ''
    },
    
    // 搜索密码
    searchPassword() {
      const inputEmail = this.forgotPasswordEmail ? this.forgotPasswordEmail.trim() : ''
      if (!inputEmail) {
        uni.showToast({
          title: '请输入邮箱地址',
          icon: 'none'
        })
        return
      }
      
      try {
        // 获取本地用户数据
        const users = uni.getStorageSync('users')
        console.log('本地存储的users数据:', users)
        
        if (!users) {
          console.log('本地存储中没有users数据')
          this.passwordNotFound = true
          this.foundPassword = ''
          uni.showToast({
            title: '本地没有用户数据，请先注册',
            icon: 'none'
          })
          return
        }
        
        const userList = JSON.parse(users)
        console.log('解析后的用户列表:', userList)
        console.log('搜索的邮箱:', inputEmail)
        
        // 显示所有用户邮箱用于调试
        const allEmails = userList.map(u => u.email).filter(email => !!email)
        console.log('所有注册的邮箱:', allEmails)
        
        // 保存可用邮箱列表
        this.availableEmails = allEmails
        
        const targetEmail = this.normalizeEmail(inputEmail)
        const user = userList.find(u => this.normalizeEmail(u.email) === targetEmail)
        console.log('找到的用户:', user)
        
        if (user && user.password) {
          this.foundPassword = user.password
          this.passwordNotFound = false
          console.log('找到密码:', user.password)
        } else {
          this.foundPassword = ''
          this.passwordNotFound = true
          console.log('未找到匹配的用户或密码')
        }
      } catch (error) {
        console.error('搜索密码失败:', error)
        this.foundPassword = ''
        this.passwordNotFound = true
        uni.showToast({
          title: '搜索失败，请重试',
          icon: 'error'
        })
      }
    },
    
    // 复制密码
    copyPassword() {
      if (this.foundPassword) {
        uni.setClipboardData({
          data: this.foundPassword,
          success: () => {
            uni.showToast({
              title: '密码已复制到剪贴板',
              icon: 'success'
            })
          }
        })
      }
    },
    
    // 选择邮箱
    selectEmail(email) {
      this.forgotPasswordEmail = email
      // 自动搜索选中的邮箱
      this.searchPassword()
    },
    
    // 手动设置密码
    setManualPassword() {
      if (!this.manualPassword.trim()) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }
      
      const rawEmail = this.forgotPasswordEmail ? this.forgotPasswordEmail.trim() : ''
      const normalizedEmail = this.normalizeEmail(rawEmail)
      const trimmedPassword = this.manualPassword.trim()
      
      if (!rawEmail) {
        uni.showToast({
          title: '请先输入邮箱地址',
          icon: 'none'
        })
        return
      }
      
      try {
        // 获取本地用户数据
        const users = uni.getStorageSync('users')
        let userList = []
        
        if (users) {
          userList = JSON.parse(users)
        }
        
        let userIndex = userList.findIndex(u => this.normalizeEmail(u.email) === normalizedEmail)
        
        if (userIndex !== -1) {
          // 更新用户密码
          userList[userIndex] = {
            ...userList[userIndex],
            password: trimmedPassword
          }
        } else {
          // 创建新的本地账户记录，避免再次提示账号不存在
          const newUser = this.createLocalUserRecord(rawEmail, trimmedPassword)
          userList.push(newUser)
          userIndex = userList.length - 1
        }
        
        uni.setStorageSync('users', JSON.stringify(userList))
        const updatedUser = userList[userIndex]
        
        // 同步当前用户信息中的密码（如果邮箱匹配）
        const currentUserRaw = uni.getStorageSync('currentUser')
        if (currentUserRaw) {
          try {
            const currentUser = JSON.parse(currentUserRaw)
            if (this.normalizeEmail(currentUser.email) === normalizedEmail) {
              const mergedCurrentUser = {
                ...currentUser,
                password: trimmedPassword,
                id: currentUser.id || updatedUser.id,
                offline_id: currentUser.offline_id || updatedUser.offline_id
              }
              uni.setStorageSync('currentUser', JSON.stringify(mergedCurrentUser))
            }
          } catch (parseError) {
            console.warn('解析当前用户信息失败，无法同步密码:', parseError)
          }
        }
        
        this.availableEmails = userList.map(u => u.email).filter(email => !!email)
        this.foundPassword = trimmedPassword
        this.passwordNotFound = false
        this.manualPassword = ''
        
        uni.showToast({
          title: '密码设置成功',
          icon: 'success'
        })
        
        // 自动刷新搜索结果，确保界面展示更新后的密码
        setTimeout(() => {
          this.searchPassword()
        }, 300)
      } catch (error) {
        console.error('设置密码失败:', error)
        uni.showToast({
          title: '设置密码失败',
          icon: 'error'
        })
      }
    },
    
    // 自动填充相关方法
    loadAvailableEmails() {
      try {
        const users = uni.getStorageSync('users')
        if (users) {
          const userList = JSON.parse(users)
          this.availableEmails = userList.map(u => u.email).filter(email => email)
          console.log('加载可用邮箱列表:', this.availableEmails)
        }
      } catch (error) {
        console.error('加载可用邮箱失败:', error)
      }
    },
    
    // 邮箱输入事件
    onEmailInput(e) {
      this.formData.email = e.detail.value
      this.filterEmailSuggestions(e.detail.value)
    },
    
    onEmailBlur() {
      // 延迟隐藏建议列表，允许点击
      setTimeout(() => {
        this.showAutoFillMenu = false
      }, 200)
    },
    
    // 密码输入事件
    onPasswordInput(e) {
      this.formData.password = e.detail.value
    },
    
    onPasswordBlur() {
      // 密码输入框失焦时的处理
    },
    
    // 过滤邮箱建议
    filterEmailSuggestions(input) {
      if (!input || input.length < 1) {
        this.autoFillSuggestions = []
        this.showAutoFillMenu = false
        return
      }
      
      const suggestions = this.availableEmails.filter(email => 
        email.toLowerCase().includes(input.toLowerCase())
      )
      
      this.autoFillSuggestions = suggestions.slice(0, 5) // 最多显示5个建议
      this.showAutoFillMenu = suggestions.length > 0
    },
    
    // 自动填充邮箱
    autoFillEmail() {
      if (this.availableEmails.length === 0) {
        uni.showToast({
          title: '没有可用的邮箱',
          icon: 'none'
        })
        return
      }
      
      // 显示邮箱选择菜单
      uni.showActionSheet({
        itemList: this.availableEmails,
        success: (res) => {
          this.formData.email = this.availableEmails[res.tapIndex]
          // 自动填充对应的密码
          this.autoFillPasswordByEmail(this.formData.email)
        }
      })
    },
    
    // 自动填充密码
    autoFillPassword() {
      if (!this.formData.email) {
        uni.showToast({
          title: '请先输入邮箱',
          icon: 'none'
        })
        return
      }
      
      this.autoFillPasswordByEmail(this.formData.email)
    },
    
    // 根据邮箱自动填充密码
    autoFillPasswordByEmail(email) {
      try {
        const users = uni.getStorageSync('users')
        if (!users) {
          uni.showToast({
            title: '本地没有用户数据',
            icon: 'none'
          })
          return
        }
        
        const userList = JSON.parse(users)
        const user = userList.find(u => u.email === email)
        
        if (user && user.password) {
          this.formData.password = user.password
          uni.showToast({
            title: '密码已自动填充',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '未找到该邮箱的密码',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('自动填充密码失败:', error)
        uni.showToast({
          title: '自动填充失败',
          icon: 'error'
        })
      }
    },
    
    // 选择邮箱建议
    selectEmailSuggestion(email) {
      this.formData.email = email
      this.showAutoFillMenu = false
      this.autoFillPasswordByEmail(email)
    },
    
    navigateToIndex() {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    },
    
    
    // 清除其他用户的本地数据，确保数据隔离
    clearOtherUserData(currentUserId) {
      try {
        console.log('清除其他用户数据，当前用户ID:', currentUserId)
        
        // 获取所有本地存储的键
        const allKeys = uni.getStorageInfoSync().keys
        
        // 需要清除的用户相关数据键
        const userDataKeys = [
          'friends_list_',
          'friend_requests_',
          'user_settings_',
          'user_profile_',
          'game_data_',
          'inventory_',
          'buildings_',
          'tech_',
          'survival_'
        ]
        
        // 清除所有其他用户的数据
        allKeys.forEach(key => {
          // 检查是否是用户相关的数据键
          const isUserData = userDataKeys.some(prefix => key.startsWith(prefix))
          
          if (isUserData) {
            // 提取键中的用户ID
            const keyUserId = key.split('_').pop()
            
            // 如果不是当前用户的数据，则清除
            if (keyUserId && keyUserId !== currentUserId.toString()) {
              console.log('清除其他用户数据:', key)
              uni.removeStorageSync(key)
            }
          }
        })
        
        console.log('数据隔离完成')
      } catch (error) {
        console.error('清除其他用户数据失败:', error)
      }
    },

    // 邮箱地址规范化
    normalizeEmail(email) {
      return (email || '').trim().toLowerCase()
    },
    
    createLocalUserRecord(email, password) {
      const timestamp = Date.now().toString()
      const createdAt = new Date().toISOString()
      const nameFromEmail = email ? email.split('@')[0] || email : `用户${timestamp}`
      return {
        id: `local_${timestamp}`,
        offline_id: `offline_${timestamp}`,
        name: nameFromEmail,
        email,
        password,
        role: 'user',
        status: 'active',
        createdAt,
        created_at: createdAt
      }
    }
  }
}
</script>

<style scoped>
/* CSS变量定义 - 作为后备方案，确保在所有平台都能正常工作 */
:root {
  --primary-color: #7B68EE;
  --primary-hover: #6A5ACD;
  --primary-light: #9B88FF;
  --secondary-color: #48BB78;
  --danger-color: #F56565;
  --warning-color: #ED8936;
  --text-primary: #2D3748;
  --text-secondary: #4A5568;
  --text-light: #718096;
  --bg-primary: #FFFFFF;
  --bg-secondary: #F7FAFC;
  --bg-card: #FFFFFF;
  --border-color: #E2E8F0;
  --border-radius-base: 12px;
  --border-radius-lg: 16px;
  --shadow-light: 0 2px 8px rgba(0, 0, 0, 0.1);
  --shadow-medium: 0 8px 25px rgba(0, 0, 0, 0.15);
  --shadow-heavy: 0 20px 40px rgba(0, 0, 0, 0.2);
  --transition-base: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  --transition-fast: all 0.2s ease;
}

/* 基础布局 */
.login-container {
  height: 100vh;
  max-height: 100vh;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  animation: fadeInUp 0.8s ease-out;
  box-sizing: border-box;
}

/* 背景装饰 */
.login-container::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: 
    radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(255, 255, 255, 0.05) 0%, transparent 50%);
  animation: float 20s ease-in-out infinite;
  pointer-events: none;
  z-index: 0;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  33% { transform: translateY(-20px) rotate(1deg); }
  66% { transform: translateY(10px) rotate(-1deg); }
}

/* 头部区域 */
.login-header {
  text-align: center;
  margin-bottom: 15px;
  margin-top: 10px;
  animation: fadeIn 0.6s ease-out 0.2s both;
  position: relative;
  z-index: 1;
  flex-shrink: 0;
}

.login-logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

.login-logo image {
  width: 55px;
  height: 55px;
  margin-right: 10px;
  animation: logoBounce 0.8s ease-out 0.4s both;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
}

.logo-text {
  font-size: 22px;
  font-weight: 700;
  background: linear-gradient(90deg, #ffffff, #f0f0f0);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* 兼容性处理：如果background-clip不支持，使用白色作为后备 */
  @supports not (background-clip: text) {
    color: #ffffff;
    background: none;
  }
}

.login-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.login-subtitle {
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.connection-status-enhanced {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 24rpx;
  padding: 16rpx 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.connection-status-enhanced:hover {
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.15);
}

.status-content {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.status-indicator {
  position: relative;
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-indicator.online {
  background-color: #4CAF50;
  box-shadow: 0 0 10rpx rgba(76, 175, 80, 0.5);
}

.status-indicator.offline {
  background-color: #f44336;
  box-shadow: 0 0 10rpx rgba(244, 67, 54, 0.5);
}

.status-pulse {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-indicator.online .status-pulse {
  background-color: rgba(76, 175, 80, 0.6);
}

.status-indicator.offline .status-pulse {
  background-color: rgba(244, 67, 54, 0.6);
}

@keyframes pulse {
  0% {
    transform: scale(0.95);
    opacity: 0.7;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.4;
  }
  100% {
    transform: scale(0.95);
    opacity: 0.7;
  }
}

.status-text {
  color: white;
  font-size: 26rpx;
  font-weight: 500;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.refresh-btn-enhanced {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  min-width: 140rpx;
  height: 56rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
  text-align: center;
}

.refresh-btn-enhanced:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.2) 100%);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  transform: translateY(-1rpx);
}

.refresh-btn-enhanced:active:not(:disabled) {
  transform: translateY(0);
}

.refresh-btn-enhanced:disabled {
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.5);
  cursor: not-allowed;
}

.refresh-icon {
  font-size: 28rpx;
  display: inline-block;
  transition: transform 0.3s ease;
}

.refresh-btn-enhanced:not(:disabled):hover .refresh-icon {
  transform: rotate(90deg);
}

.refresh-btn-enhanced:disabled .refresh-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 表单内容容器 */
.form-content {
  width: 100%;
  max-width: 380px;
  background: var(--bg-card);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-heavy);
  padding: 24px;
  margin-bottom: 20px;
  transition: var(--transition-base);
  animation: slideInUp 0.8s ease-out 0.4s both;
  position: relative;
  z-index: 1;
  border: 1px solid rgba(255, 255, 255, 0.2);
  flex-shrink: 0;
}

.form-content:hover {
  transform: translateY(-5px);
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
}

/* 表单组 */
.form-group {
  margin-bottom: 18px;
  animation: fadeInUp 0.6s ease-out 0.6s both;
  position: relative;
  z-index: 2;
}

.form-group:nth-child(2) {
  animation-delay: 0.7s;
}

.form-group:nth-child(3) {
  animation-delay: 0.8s;
}

.form-group:nth-child(4) {
  animation-delay: 0.9s;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  transition: var(--transition-fast);
}

.form-group:focus-within .form-label {
  color: var(--primary-color);
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  border: 2px solid #E2E8F0;
  border-radius: 12px;
  background: #F7FAFC;
  transition: all 0.3s ease;
}

.input-icon {
  padding: 0 16px;
  font-size: 16px;
  color: #718096;
  user-select: none;
}

.form-input {
  flex: 1;
  padding: 16px 0;
  border: none;
  background: transparent;
  font-size: 16px;
  color: #2D3748;
  outline: none;
}

.form-input:focus {
  outline: none;
}

.input-wrapper:focus-within {
  border-color: #2D3748;
  background: #ffffff;
  box-shadow: 0 0 0 3px rgba(45, 55, 72, 0.1);
}

.form-input::placeholder {
  color: #A0AEC0;
}

.toggle-password {
  padding: 0 16px;
  font-size: 16px;
  color: #718096;
  cursor: pointer;
  user-select: none;
}

.toggle-password:hover {
  color: var(--primary-color);
}

/* 主要按钮 */
.btn-primary {
  width: 100%;
  padding: 16px 24px;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white !important;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
  margin-bottom: 16px;
  animation: fadeInUp 0.6s ease-out 1.3s both;
  display: block;
  min-height: 48px;
  line-height: 1.2;
  text-align: center;
}

.btn-primary::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.btn-primary:hover::before {
  left: 100%;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
  background: linear-gradient(135deg, #66BB6A 0%, #4CAF50 100%);
}

.btn-primary:active {
  transform: translateY(0);
}

.btn-primary:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.auth-btn {
  animation: fadeInUp 0.6s ease-out 1.3s both;
}

.loading-icon {
  margin-right: 8px;
  animation: spin 1s linear infinite;
}

/* 按钮文本样式 */
.btn-primary text {
  color: white !important;
  font-size: 16px;
  font-weight: 600;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 错误消息 */
.error-message {
  color: var(--danger-color);
  font-size: 12px;
  margin-top: 5px;
  display: block;
  animation: shake 0.5s ease-in-out;
  text-align: center;
  margin-bottom: 20px;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 成功消息 */
.success-message {
  color: var(--secondary-color);
  font-size: 14px;
  text-align: center;
  padding: 12px;
  background: rgba(72, 187, 120, 0.1);
  border-radius: var(--border-radius-base);
  margin-bottom: 16px;
  animation: fadeInUp 0.6s ease-out;
}

/* 微信登录区域 */
.wechat-login-section {
  margin: 24px 0;
  animation: fadeInUp 0.6s ease-out 1.2s both;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
  gap: 12px;
}

.divider-line {
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, transparent, #E2E8F0, transparent);
}

.divider-text {
  color: #A0AEC0;
  font-size: 14px;
  font-weight: 500;
}

.btn-wechat {
  width: 100%;
  padding: 16px 24px;
  background: linear-gradient(135deg, #07c160 0%, #06ae56 100%);
  color: white !important;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(7, 193, 96, 0.3);
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-height: 48px;
  line-height: 1.2;
}

.btn-wechat::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.btn-wechat:hover::before {
  left: 100%;
}

.btn-wechat:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(7, 193, 96, 0.4);
  background: linear-gradient(135deg, #06ae56 0%, #059e4e 100%);
}

.btn-wechat:active:not(:disabled) {
  transform: translateY(0);
}

.btn-wechat:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.btn-wechat text {
  color: white !important;
  font-size: 16px;
  font-weight: 600;
}

.wechat-icon {
  font-size: 20px;
}

/* 认证链接区域 */
.auth-links {
  display: flex;
  flex-direction: column;
  gap: 16px;
  animation: fadeInUp 0.6s ease-out 1.4s both;
}

.forgot-password-btn {
  color: #ff6b6b;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  text-align: center;
  transition: all 0.3s ease;
  text-decoration: underline;
  text-decoration-color: #ff6b6b;
}

.forgot-password-btn:hover {
  color: #ffffff;
  text-decoration-color: #ffffff;
  transform: scale(1.05);
  text-shadow: 0 0 10px rgba(255, 107, 107, 0.8);
}

/* 底部链接 - 在卡片内部 */
.register-link {
  text-align: center;
  position: relative;
  z-index: 2;
  padding: 0;
}

.register-text {
  color: #ffffff;
  font-size: 14px;
  margin-right: 8px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.register-btn {
  color: #7089fa;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: underline;
  text-decoration-color: #7089fa;
  font-size: 14px;
  text-shadow: 0 0 8px rgba(112, 137, 250, 0.5);
  position: relative;
}

.register-btn:hover {
  color: #ffffff;
  text-decoration-color: #ffffff;
  transform: scale(1.05);
  text-shadow: 0 0 15px rgba(255, 255, 255, 0.8), 0 0 25px rgba(112, 137, 250, 0.6);
}

/* 动画定义 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes logoBounce {
  0% {
    opacity: 0;
    transform: scale(0.5) rotate(-180deg);
  }
  50% {
    transform: scale(1.1) rotate(0deg);
  }
  100% {
    opacity: 1;
    transform: scale(1) rotate(0deg);
  }
}

/* 找回密码弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  padding: 40rpx;
  backdrop-filter: blur(4rpx);
}

.forgot-password-modal {
  max-width: 600rpx;
  max-height: 80vh;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20rpx);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
}

.modal-close {
  font-size: 28rpx;
  cursor: pointer;
  padding: 8rpx;
  border-radius: 50%;
  transition: background-color 0.3s ease;
}

.modal-close:active {
  background: rgba(255, 255, 255, 0.2);
}

.modal-body {
  max-height: 60vh;
  overflow-y: auto;
  padding: 30rpx;
  background: white;
}

.forgot-password-info {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  border-left: 4rpx solid #ff6b6b;
}

.info-text {
  font-size: 24rpx;
  color: #636e72;
  line-height: 1.5;
}

.password-result {
  margin: 20rpx 0;
  padding: 20rpx;
  background: #e8f5e8;
  border-radius: 8rpx;
  border: 1rpx solid #4caf50;
}

.result-label {
  font-size: 26rpx;
  color: #2d3436;
  font-weight: bold;
  margin-bottom: 12rpx;
  display: block;
}

.password-display {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.password-text {
  flex: 1;
  font-size: 24rpx;
  color: #2d3436;
  font-family: 'Courier New', monospace;
  background: white;
  padding: 12rpx;
  border-radius: 6rpx;
  border: 1rpx solid #ddd;
}

.copy-btn {
  background: #4caf50;
  color: white;
  padding: 12rpx 20rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}

.copy-btn:active {
  background: #45a049;
  transform: scale(0.98);
}

.no-password-result {
  margin: 20rpx 0;
  padding: 20rpx;
  background: #fff3cd;
  border-radius: 8rpx;
  border: 1rpx solid #ffc107;
  text-align: center;
}

.no-password-text {
  font-size: 24rpx;
  color: #856404;
}

.available-emails {
  margin-top: 20rpx;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.available-emails-title {
  font-size: 22rpx;
  color: #495057;
  font-weight: bold;
  margin-bottom: 12rpx;
  display: block;
}

.email-item {
  margin-bottom: 8rpx;
}

.email-text {
  font-size: 20rpx;
  color: #007bff;
  cursor: pointer;
  text-decoration: underline;
  padding: 8rpx 12rpx;
  border-radius: 4rpx;
  transition: all 0.3s ease;
  display: inline-block;
}

.email-text:hover {
  background: #e3f2fd;
  color: #0056b3;
}

.manual-password-section {
  margin-top: 20rpx;
  padding: 16rpx;
  background: #f0f8ff;
  border-radius: 8rpx;
  border: 1rpx solid #007bff;
}

.manual-password-title {
  font-size: 22rpx;
  color: #495057;
  font-weight: bold;
  margin-bottom: 12rpx;
  display: block;
}

.manual-password-input {
  display: flex;
  gap: 12rpx;
  align-items: center;
}

.manual-password-input .form-input {
  flex: 1;
  padding: 12rpx;
  border: 1rpx solid #ddd;
  border-radius: 6rpx;
  font-size: 22rpx;
}

.set-password-btn {
  background: #007bff;
  color: white;
  padding: 12rpx 20rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
  cursor: pointer;
  border: none;
  transition: all 0.3s ease;
}

.set-password-btn:active {
  background: #0056b3;
  transform: scale(0.98);
}

/* 自动填充相关样式 */
.auto-fill-btn {
  font-size: 24rpx;
  color: #667eea;
  cursor: pointer;
  padding: 8rpx;
  border-radius: 4rpx;
  transition: all 0.3s ease;
  margin-left: 8rpx;
}

.auto-fill-btn:hover {
  background: #f0f8ff;
  transform: scale(1.1);
}

.auto-fill-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1rpx solid #e9ecef;
  border-radius: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  z-index: 1000;
  max-height: 300rpx;
  overflow-y: auto;
  margin-top: 4rpx;
}

.suggestion-item {
  padding: 16rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-item:hover {
  background: #f8f9fa;
}

.suggestion-item:active {
  background: #e9ecef;
}

.suggestion-text {
  font-size: 26rpx;
  color: #495057;
}

/* APP端特有的自动填充样式 */
/* #ifdef APP-PLUS */
.auto-fill-btn {
  background: rgba(102, 126, 234, 0.1);
  border: 1rpx solid rgba(102, 126, 234, 0.3);
}

.auto-fill-btn:active {
  background: rgba(102, 126, 234, 0.2);
  transform: scale(0.95);
}
/* #endif */

.modal-actions {
  display: flex;
  gap: 16rpx;
  margin-top: 30rpx;
}

.modal-btn {
  flex: 1;
  height: 70rpx;
  border-radius: 8rpx;
  font-size: 26rpx;
  font-weight: bold;
  border: none;
  transition: all 0.3s ease;
}

.modal-btn.primary {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
}

.modal-btn.primary:active {
  transform: scale(0.98);
}

.modal-btn.secondary {
  background: #f8f9fa;
  color: #636e72;
  border: 2rpx solid #e9ecef;
}

.modal-btn.secondary:active {
  background: #e9ecef;
}

.modal-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
/* 隐藏浏览器自带的密码可见按钮（避免出现双眼睛图标） */
input[type="password"]::-ms-reveal,
input[type="password"]::-ms-clear {
  display: none;
}

input[type="password"]::-webkit-credentials-auto-fill-button,
input[type="password"]::-webkit-clear-button,
input[type="password"]::-webkit-inner-spin-button {
  display: none !important;
}
</style>
